import React, { useState, useEffect, useRef, useMemo } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Checkbox,
  FormControlLabel,
  List,
  ListItem,
  ListItemText,
  ListItemAvatar,
  Avatar,
  Divider,
  Paper,
  InputAdornment,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Chip,
  Alert,
  Snackbar,
  Card,
  CardContent,
  IconButton,
  CircularProgress
} from '@mui/material';
import { Search as SearchIcon, AccessTime as AccessTimeIcon, Delete as DeleteIcon, Schedule as ScheduleIcon, Image as ImageIcon, Close as CloseIcon } from '@mui/icons-material';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider, DateTimePicker } from '@mui/x-date-pickers';
import { zhCN } from 'date-fns/locale';
import { dbService } from '../services/dbService';
import schedulerService, { TASK_TYPES, TASK_STATUS } from '../services/schedulerService';

const MassSender = ({ handleSendMessage }) => {
  // 初始化全局定时器服务
  // 注意：这个组件不会渲染任何内容，只会在组件挂载时初始化服务
  // SchedulerInitializer组件会注册任务处理函数并启动定时检查
  // 状态管理
  const [contacts, setContacts] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [debouncedSearchText, setDebouncedSearchText] = useState('');
  const [selectedContacts, setSelectedContacts] = useState([]);
  const [messageText, setMessageText] = useState('');
  const [scheduleTime, setScheduleTime] = useState(new Date(Date.now() + 30 * 60000)); // 默认30分钟后
  const [isScheduled, setIsScheduled] = useState(false);
  const [loading, setLoading] = useState(true);
  const [openPreview, setOpenPreview] = useState(false);
  const [scheduledTasks, setScheduledTasks] = useState([]);
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: '',
    severity: 'success'
  });
  
  // 图片上传相关状态
  const [selectedImage, setSelectedImage] = useState(null);
  const [imagePreview, setImagePreview] = useState('');
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef(null);
  
  // 防抖处理搜索
  const searchDebounceRef = useRef(null);

  // 加载通讯录数据和定时任务数据
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        // 从IndexedDB中获取通讯录数据
        const addressBookData = await dbService.get(dbService.getStoreNames().ADRESSBOOK, 'addressbook');
        
        if (addressBookData && addressBookData.data && addressBookData.data.length > 0) {
          console.log('从IndexedDB加载通讯录数据成功');
          setContacts(addressBookData.data);
        } else {
          console.log('未找到通讯录数据');
        }
        
        // 从全局定时器服务获取定时任务数据
        const allTasks = schedulerService.getAllTasks();
        // 只显示群发消息类型的任务
        const massTasks = allTasks.filter(task => task.type === TASK_TYPES.MASS_MESSAGE);
        if (massTasks.length > 0) {
          console.log('从全局定时器服务加载群发任务数据成功');
          setScheduledTasks(massTasks);
        } else {
          console.log('未找到群发任务数据或数据为空');
          //setScheduledTasks([]);
        }
      } catch (error) {
        console.error('加载数据失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadData();
  }, []);

  // 处理搜索输入变化，使用防抖优化性能
  const handleSearch = (e) => {
    const value = e.target.value;
    setSearchText(value);
    
    // 清除之前的定时器
    if (searchDebounceRef.current) {
      clearTimeout(searchDebounceRef.current);
    }
    
    // 设置新的定时器，150ms后更新搜索文本
    searchDebounceRef.current = setTimeout(() => {
      setDebouncedSearchText(value);
    }, 150);
  };
  
  // 在组件卸载时清除定时器
  useEffect(() => {
      return () => {
        if (searchDebounceRef.current) {
          clearTimeout(searchDebounceRef.current);
        }
      };
    }, []);

  // 使用useMemo缓存过滤结果，避免不必要的重新计算
  const filteredContacts = useMemo(() => {
      return contacts.filter(contact => {
        if (!debouncedSearchText) return true;
        const searchLower = debouncedSearchText.toLowerCase();
        return (
          (contact.name && contact.name.toLowerCase().includes(searchLower)) ||
          (contact.remark && contact.remark.toLowerCase().includes(searchLower)) ||
          (contact.alias && contact.alias.toLowerCase().includes(searchLower))
        );
      });
    }, [contacts, debouncedSearchText]);

  // 处理联系人选择
  const handleContactSelect = (contact) => {
    setSelectedContacts(prev => {
      const isSelected = prev.some(c => c.id === contact.id);
      if (isSelected) {
        return prev.filter(c => c.id !== contact.id);
      } else {
        return [...prev, contact];
      }
    });
  };

  // 检查联系人是否被选中
  const isContactSelected = (contactId) => {
    return selectedContacts.some(contact => contact.id === contactId);
  };

  // 处理全选
  const handleSelectAll = () => {
    if (selectedContacts.length === filteredContacts.length) {
      setSelectedContacts([]);
    } else {
      setSelectedContacts([...filteredContacts]);
    }
  };

  // 处理移除选中的联系人
  const handleRemoveContact = (contactId) => {
    setSelectedContacts(prev => prev.filter(contact => contact.id !== contactId));
  };

  // 处理预览对话框
  const handleOpenPreview = () => {
    if (messageText.trim() === '' && !selectedImage) {
      setSnackbar({
        open: true,
        message: '请输入要发送的消息内容或选择图片',
        severity: 'warning'
      });
      return;
    }
    if (selectedContacts.length === 0) {
      setSnackbar({
        open: true,
        message: '请选择至少一个联系人',
        severity: 'warning'
      });
      return;
    }
    setOpenPreview(true);
  };

  // 处理关闭预览
  const handleClosePreview = () => {
    setOpenPreview(false);
  };

  // 处理图片选择
  const handleImageSelect = (event) => {
    const file = event.target.files[0];
    if (file && file.type.startsWith('image/')) {
      setSelectedImage(file);
      const reader = new FileReader();
      reader.onload = (e) => {
        setImagePreview(e.target.result);
      };
      reader.readAsDataURL(file);
    }
  };
  
  // 取消选择的图片
  const handleCancelImage = () => {
    setSelectedImage(null);
    setImagePreview('');
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 处理创建群发任务
  const handleCreateTask = async () => {
    // 显示处理中状态
    setSnackbar({
      open: true,
      message: '正在处理群发消息...',
      severity: 'info'
    });
    
    try {
      // 如果是定时发送，创建定时任务
      if (isScheduled) {
        // 创建新的定时任务对象
        const newTask = {
          id: Date.now(), // 使用时间戳作为唯一ID
          type: TASK_TYPES.MASS_MESSAGE, // 设置任务类型为群发消息
          recipients: [...selectedContacts],
          message: selectedImage ? imagePreview : messageText,
          scheduledTime: scheduleTime,
          createdAt: new Date(),
          status: TASK_STATUS.PENDING,
          msgType: selectedImage ? 3 : 1, // 3表示图片消息，1表示文本消息
        };
        
        // 使用全局定时器服务添加任务
        await schedulerService.addTask(newTask);
        
        // 更新本地任务列表显示
        setScheduledTasks(prevTasks => [...prevTasks, newTask]);
        
        // 显示成功消息
        setSnackbar({
          open: true,
          message: '定时群发任务创建成功！',
          severity: 'success'
        });
        
        // 重置表单
        setMessageText('');
        setSelectedContacts([]);
        setIsScheduled(false);
        setScheduleTime(new Date(Date.now() + 30 * 60000));
        handleCancelImage(); // 清除已选图片
        setOpenPreview(false);
      } else {
        // 立即发送消息
        // 遍历所有选中的联系人，为每个联系人发送消息
        let successCount = 0;
        let failCount = 0;
        
        for (const contact of selectedContacts) {
          try {
            // 为每个联系人创建消息对象
            const messageObj = {
              id: Date.now() + Math.floor(Math.random() * 1000), // 确保ID唯一
              content: selectedImage ? imagePreview : messageText,
              msgType: selectedImage ? 3 : 1, // 3表示图片消息，1表示文本消息
              timestamp: new Date().toISOString(),
              status: 'pending'
            };
            
            // 如果是图片消息，需要将图片转换为Base64格式
            if (selectedImage) {
              const reader = new FileReader();
              reader.readAsDataURL(selectedImage);
              await new Promise((resolve, reject) => {
                reader.onload = () => {
                  const base64Image = reader.result.split(',')[1]; // 移除Data URL前缀
                  resolve(base64Image);
                };
                reader.onerror = reject;
              }).then(async (base64Image) => {
                // 调用ChatRoom组件的handleSendMessage方法发送图片
                await handleSendMessage(messageObj, base64Image, false, contact.id);
                successCount++;
              });
            } else {
              // 发送文本消息
              await handleSendMessage(messageObj, null, false, contact.id);
              successCount++;
            }
          } catch (error) {
            console.error(`向联系人 ${contact.name} 发送消息失败:`, error);
            failCount++;
          }
        }
        
        // 显示发送结果
        setSnackbar({
          open: true,
          message: `群发完成！成功: ${successCount}, 失败: ${failCount}`,
          severity: successCount > 0 ? 'success' : 'error'
        });
        
        // 重置表单
        setMessageText('');
        setSelectedContacts([]);
        handleCancelImage(); // 清除已选图片
        setOpenPreview(false);
      }
    } catch (error) {
      console.error('群发消息失败:', error);
      setSnackbar({
        open: true,
        message: '群发消息失败，请重试',
        severity: 'error'
      });
    }
  };

  // 处理Snackbar关闭
  const handleSnackbarClose = () => {
    setSnackbar({ ...snackbar, open: false });
  };
  
  // 当组件挂载时，从全局定时器服务获取最新任务状态
    useEffect(() => {
      // 定义刷新任务列表的函数
      const refreshTasks = () => {
        const allTasks = schedulerService.getAllTasks();
        // 只显示群发消息类型的任务
        const massTasks = allTasks.filter(task => task.type === TASK_TYPES.MASS_MESSAGE);
        setScheduledTasks(massTasks);
      };
      
      // 初始加载任务列表
      refreshTasks();
      
      // 设置定时器，每10秒刷新一次任务列表
      const refreshTimerId = setInterval(refreshTasks, 10000);
      
      // 组件卸载时清除定时器
      return () => {
        clearInterval(refreshTimerId);
      };
    }, []);
  
  // 清空已取消和已完成的定时任务
  const handleClearCancelledTasks = async () => {
    // 使用全局定时器服务清理任务
    await schedulerService.cleanupTasks();
    
    // 刷新本地任务列表
    const allTasks = schedulerService.getAllTasks();
    const massTasks = allTasks.filter(task => task.type === TASK_TYPES.MASS_MESSAGE);
    setScheduledTasks(massTasks);
    
    setSnackbar({
      open: true,
      message: '已清空取消和已完成的定时任务',
      severity: 'success'
    });
  };
  
  // 处理取消定时任务
  const handleCancelTask = async (taskId) => {
    // 使用全局定时器服务取消任务
    await schedulerService.cancelTask(taskId);
    
    // 更新本地任务列表
    setScheduledTasks(prevTasks => {
      const updatedTasks = prevTasks.map(task => 
        task.id === taskId ? { ...task, status: TASK_STATUS.CANCELLED } : task
      );
      return updatedTasks;
    });
    
    setSnackbar({
      open: true,
      message: '已取消定时发送任务',
      severity: 'info'
    });
  };
  
  // 格式化日期显示
  const formatDateTime = (date) => {
    return date.toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  return (
    <Box sx={{ height: '100%', width: '100%', bgcolor: '#f5f5f5', display: 'flex', flexDirection: 'column' }}>
      {/* 标题栏 */}
      <Box sx={{ p: 2, borderBottom: '1px solid #e0e0e0' }}>
        <Typography variant="h6" sx={{ fontWeight: 'medium' }}>群发助手</Typography>
      </Box>
      
      {/* 主内容区 */}
      <Box sx={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
        {/* 左侧联系人选择区 */}
        <Box sx={{ width: '40%', borderRight: '1px solid #e0e0e0', display: 'flex', flexDirection: 'column' }}>
          <Box sx={{ p: 2, borderBottom: '1px solid #e0e0e0' }}>
            <Typography variant="subtitle1" sx={{ mb: 1 }}>选择联系人</Typography>
            <TextField
              fullWidth
              size="small"
              placeholder="搜索联系人"
              value={searchText}
              onChange={handleSearch}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
              sx={{ 
                '& .MuiOutlinedInput-root': {
                  borderRadius: 2,
                  backgroundColor: '#fff'
                }
              }}
            />
          </Box>
          
          <Box sx={{ p: 1, borderBottom: '1px solid #e0e0e0' }}>
            <FormControlLabel
              control={
                <Checkbox 
                  checked={selectedContacts.length === filteredContacts.length && filteredContacts.length > 0}
                  indeterminate={selectedContacts.length > 0 && selectedContacts.length < filteredContacts.length}
                  onChange={handleSelectAll}
                />
              }
              label="全选"
            />
          </Box>
          
          <Box sx={{ flex: 1, overflow: 'auto' }}>
            {loading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
                <Typography>加载联系人中...</Typography>
              </Box>
            ) : (
              <List sx={{ width: '100%', bgcolor: 'background.paper', p: 0 }}>
                {filteredContacts.map((contact) => (
                  <React.Fragment key={contact.id}>
                    <ListItem 
                      button
                      onClick={() => handleContactSelect(contact)}
                      sx={{ 
                        p: 1.5,
                        bgcolor: isContactSelected(contact.id) ? '#e3f2fd' : 'transparent',
                        '&:hover': {
                          bgcolor: isContactSelected(contact.id) ? '#e3f2fd' : '#f0f0f0'
                        }
                      }}
                    >
                      <Checkbox 
                        checked={isContactSelected(contact.id)}
                        onChange={() => handleContactSelect(contact)}
                        sx={{ mr: 1 }}
                      />
                      <ListItemAvatar>
                        <Avatar src={contact.avatar} alt={contact.name} />
                      </ListItemAvatar>
                      <ListItemText
                        primary={contact.remark || contact.name}
                        secondary={contact.alias || null}
                      />
                    </ListItem>
                    <Divider variant="inset" component="li" />
                  </React.Fragment>
                ))}
              </List>
            )}
          </Box>
        </Box>
        
        {/* 右侧消息编辑区和定时任务列表 - 整体可滚动 */}
        <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', height: '100%', overflow: 'auto' }}>
          {/* 消息编辑区域：标题、已选联系人、消息编辑、定时选项和操作按钮 */}
          <Box sx={{ p: 2, display: 'flex', flexDirection: 'column' }}>
            <Typography variant="subtitle1" sx={{ mb: 2 }}>编辑群发消息</Typography>
            
            {/* 已选联系人展示 - 固定在顶部 */}
            <Paper sx={{ p: 1, mb: 2, maxHeight: '120px', overflow: 'auto' }}>
              <Typography variant="body2" sx={{ mb: 1 }}>已选择 {selectedContacts.length} 位联系人</Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                {selectedContacts.map(contact => (
                  <Chip
                    key={contact.id}
                    avatar={<Avatar src={contact.avatar} alt={contact.name} />}
                    label={contact.remark || contact.name}
                    onDelete={() => handleRemoveContact(contact.id)}
                    sx={{ m: 0.5 }}
                  />
                ))}
              </Box>
            </Paper>
            
            {/* 消息内容编辑 */}
            <TextField
              fullWidth
              multiline
              rows={2}
              placeholder="请输入要群发的消息内容..."
              value={messageText}
              onChange={(e) => setMessageText(e.target.value)}
              disabled={selectedImage !== null}
              sx={{ 
                mb: 2,
                '& .MuiOutlinedInput-root': {
                  backgroundColor: '#fff'
                },
                '& .MuiInputBase-root': {
                  resize: 'vertical',
                  overflow: 'auto'
                }
              }}
            />
            
            {/* 图片上传和预览区域 */}
            <Box sx={{ mb: 2 }}>
              <input
                type="file"
                accept="image/*"
                style={{ display: 'none' }}
                id="image-upload"
                ref={fileInputRef}
                onChange={handleImageSelect}
              />
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                <label htmlFor="image-upload">
                  <Button
                    variant="outlined"
                    component="span"
                    startIcon={<ImageIcon />}
                    disabled={messageText.trim() !== ''}
                    sx={{ mr: 1 }}
                  >
                    选择图片
                  </Button>
                </label>
                {selectedImage && (
                  <Typography variant="body2" color="text.secondary">
                    {selectedImage.name} ({Math.round(selectedImage.size / 1024)} KB)
                  </Typography>
                )}
              </Box>
              
              {/* 图片预览 */}
              {imagePreview && (
                <Paper sx={{ p: 1, mb: 1, position: 'relative' }}>
                  <IconButton
                    size="small"
                    onClick={handleCancelImage}
                    sx={{ position: 'absolute', top: 5, right: 5, bgcolor: 'rgba(255,255,255,0.7)' }}
                  >
                    <CloseIcon fontSize="small" />
                  </IconButton>
                  <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                    <img 
                      src={imagePreview} 
                      alt="预览图片" 
                      style={{ maxWidth: '100%', maxHeight: '200px', objectFit: 'contain' }} 
                    />
                  </Box>
                </Paper>
              )}
              
              {isUploading && (
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', my: 1 }}>
                  <CircularProgress size={24} sx={{ mr: 1 }} />
                  <Typography variant="body2">正在处理图片...</Typography>
                </Box>
              )}
            </Box>
            
            {/* 定时发送选项 */}
            <Paper sx={{ p: 1, mb: 2 }}>
              <FormControlLabel
                control={
                  <Checkbox 
                    checked={isScheduled}
                    onChange={(e) => setIsScheduled(e.target.checked)}
                  />
                }
                label="定时发送"
              />
              
              {isScheduled && (
                <Box sx={{ mt: 1 }}>
                  <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={zhCN}>
                    <DateTimePicker
                      label="选择发送时间"
                      value={scheduleTime}
                      onChange={(newValue) => setScheduleTime(newValue)}
                      renderInput={(params) => <TextField {...params} fullWidth size="small" />}
                      minDateTime={new Date()}
                    />
                  </LocalizationProvider>
                </Box>
              )}
            </Paper>
            
            {/* 操作按钮 */}
            <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 1 }}>
              <Button 
                variant="contained" 
                color="primary"
                onClick={handleOpenPreview}
                disabled={selectedContacts.length === 0 || (messageText.trim() === '' && !selectedImage)}
              >
                {isScheduled ? '创建定时任务' : '立即发送'}
              </Button>
            </Box>
          </Box>
          
          {/* 定时任务列表 - 作为整体滚动区域的一部分 */}
          {scheduledTasks.length > 0 && (
            <Box sx={{ 
              px: 2, 
              pb: 2, 
              borderTop: '1px solid #e0e0e0',
              bgcolor: '#f9f9f9'
            }}>
              <Box sx={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center', 
                py: 1.5,
                bgcolor: '#f9f9f9'
              }}>
                <Typography variant="subtitle1" sx={{ display: 'flex', alignItems: 'center' }}>
                  <ScheduleIcon sx={{ mr: 1 }} />
                  定时任务列表 ({scheduledTasks.filter(t => t.status === 'pending').length} 个待执行)
                </Typography>
                {(scheduledTasks.some(task => task.status === 'cancelled') || scheduledTasks.some(task => task.status === 'completed')) && (
                  <Button 
                    size="small" 
                    variant="outlined" 
                    color="error" 
                    onClick={handleClearCancelledTasks}
                  >
                    清空历史任务
                  </Button>
                )}
              </Box>
              
              <List sx={{ width: '100%', bgcolor: 'background.paper', borderRadius: 1, p: 0 }}>
                {scheduledTasks.map((task) => (
                  <Card key={task.id} sx={{ 
                    mb: 1, 
                    bgcolor: task.status === 'cancelled' ? '#f5f5f5' : 'white',
                    boxShadow: '0 1px 2px rgba(0,0,0,0.05)'
                  }}>
                    <CardContent sx={{ p: 1, '&:last-child': { pb: 1 } }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Box sx={{ display: 'flex', alignItems: 'center' }}>
                          <AccessTimeIcon fontSize="small" sx={{ mr: 0.5, color: 'text.secondary', fontSize: '0.9rem' }} />
                          <Typography variant="body2" sx={{ 
                            fontSize: '0.8rem',
                            textDecoration: task.status === 'cancelled' ? 'line-through' : 'none',
                            color: task.status === 'cancelled' ? 'text.disabled' : 'text.primary'
                          }}>
                            {formatDateTime(task.scheduledTime)}
                          </Typography>
                        </Box>
                        <Typography variant="caption" color="text.secondary" sx={{ fontSize: '0.7rem' }}>
                          {task.status === 'cancelled' ? (
                            <span style={{ color: '#f44336' }}>已取消</span>
                          ) : task.status === 'completed' ? (
                            <span style={{ color: '#4caf50' }}>已完成</span>
                          ) : (
                            <Button 
                              size="small" 
                              color="error" 
                              onClick={() => handleCancelTask(task.id)}
                              sx={{ minWidth: 'auto', p: 0.5, fontSize: '0.7rem', lineHeight: 1 }}
                            >
                              取消
                            </Button>
                          )}
                        </Typography>
                      </Box>
                      
                      <Typography variant="body2" sx={{ 
                        mt: 0.5, 
                        fontSize: '0.8rem',
                        color: task.status === 'cancelled' ? 'text.disabled' : 'text.primary',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        display: '-webkit-box',
                        WebkitLineClamp: 1,
                        WebkitBoxOrient: 'vertical'
                      }}>
                        {task.message.length > 40 ? `${task.message.substring(0, 40)}...` : task.message}
                      </Typography>
                      
                      <Box sx={{ display: 'flex', alignItems: 'center', mt: 0.5, justifyContent: 'space-between' }}>
                        <Typography variant="caption" sx={{ 
                          fontSize: '0.75rem',
                          color: task.status === 'cancelled' ? 'text.disabled' : 'text.secondary' 
                        }}>
                          {task.recipients.length} 位联系人
                        </Typography>
                        
                        <Box sx={{ display: 'flex', flexWrap: 'nowrap', gap: 0.5 }}>
                          {task.recipients.slice(0, 2).map(contact => (
                            <Chip
                              key={contact.id}
                              size="small"
                              avatar={<Avatar src={contact.avatar} alt={contact.name} sx={{ width: 16, height: 16 }} />}
                              label={contact.remark || contact.name}
                              sx={{ 
                                opacity: task.status === 'cancelled' ? 0.6 : 1,
                                height: 20,
                                '& .MuiChip-label': { fontSize: '0.65rem', px: 0.5 }
                              }}
                            />
                          ))}
                          {task.recipients.length > 2 && (
                            <Chip 
                              size="small" 
                              label={`+${task.recipients.length - 2}`} 
                              sx={{ 
                                opacity: task.status === 'cancelled' ? 0.6 : 1,
                                height: 20,
                                '& .MuiChip-label': { fontSize: '0.65rem', px: 0.5 }
                              }}
                            />
                          )}
                        </Box>
                      </Box>
                    </CardContent>
                  </Card>
                ))}
              </List>
            </Box>
          )}
        </Box>
      </Box>
      
      {/* 预览对话框 */}
      <Dialog open={openPreview} onClose={handleClosePreview} maxWidth="sm" fullWidth>
        <DialogTitle>确认{isScheduled ? '定时群发' : '群发'}消息</DialogTitle>
        <DialogContent>
          <Typography variant="subtitle2" gutterBottom>发送对象：</Typography>
          <Box sx={{ mb: 2 }}>
            {selectedContacts.map((contact, index) => (
              <React.Fragment key={contact.id}>
                <Typography component="span">{contact.remark || contact.name}</Typography>
                {index < selectedContacts.length - 1 && <Typography component="span">, </Typography>}
              </React.Fragment>
            ))}
          </Box>
          
          <Typography variant="subtitle2" gutterBottom>消息内容：</Typography>
          <Paper sx={{ p: 2, mb: 2, bgcolor: '#f9f9f9' }}>
            {selectedImage ? (
              <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>[图片消息]</Typography>
                <img 
                  src={imagePreview} 
                  alt="预览图片" 
                  style={{ maxWidth: '100%', maxHeight: '200px', objectFit: 'contain' }} 
                />
              </Box>
            ) : (
              <Typography variant="body1" sx={{ whiteSpace: 'pre-wrap' }}>{messageText}</Typography>
            )}
          </Paper>
          
          {isScheduled && (
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
              <AccessTimeIcon sx={{ mr: 1, color: 'text.secondary' }} />
              <Typography variant="body2">
                定时发送时间：{scheduleTime.toLocaleString('zh-CN', { 
                  year: 'numeric', 
                  month: '2-digit', 
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit'
                })}
              </Typography>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClosePreview}>取消</Button>
          <Button onClick={handleCreateTask} variant="contained" color="primary">
            确认{isScheduled ? '创建' : '发送'}
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 提示消息 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert onClose={handleSnackbarClose} severity={snackbar.severity}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default MassSender;